from PySide6.QtWidgets import QDialog, QVBoxLayout, QLabel, QPushButton, QScrollArea, QHBoxLayout, QSpinBox, QMessageBox
from PySide6.QtCore import Qt
from PySide6.QtGui import QPixmap, QImage, QWheelEvent
import cv2
import numpy as np
from PySide6.QtWidgets import QApplication

class ImagePreviewDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("图片预览")
        self.setModal(True)
        
        # 获取屏幕尺寸
        screen = QApplication.primaryScreen().geometry()
        self.max_width = int(screen.width() * 0.8)  # 最大宽度为屏幕的80%
        self.max_height = int(screen.height() * 0.8)  # 最大高度为屏幕的80%
        
        # 设置初始大小
        self.resize(800, 600)
        
        # 保存原始图片
        self.original_pixmap = None
        
        # 创建布局
        layout = QVBoxLayout(self)
        
        # 创建滚动区域
        scroll = QScrollArea()
        scroll.setWidgetResizable(True)
        layout.addWidget(scroll)
        
        # 创建图片标签
        self.image_label = QLabel()
        self.image_label.setAlignment(Qt.AlignCenter)
        scroll.setWidget(self.image_label)
        
        # 添加关闭按钮
        close_btn = QPushButton("关闭")
        close_btn.clicked.connect(self.close)
        layout.addWidget(close_btn, alignment=Qt.AlignCenter)
        
    def load_image(self, image_path: str):
        """加载图片"""
        try:
            pixmap = QPixmap(image_path)
            if pixmap.isNull():
                raise Exception("无法加载图片")
            
            # 保存原始图片
            self.original_pixmap = pixmap
            
            # 调整图片大小以适应窗口
            self.scale_image()
            
        except Exception as e:
            QMessageBox.warning(self, "错误", f"加载图片失败: {str(e)}")
            self.close()
            
    def scale_image(self):
        """缩放图片以适应窗口"""
        if not self.original_pixmap:
            return
            
        # 计算缩放后的尺寸
        available_width = min(self.width() - 40, self.max_width)  # 留出一些边距
        available_height = min(self.height() - 80, self.max_height)  # 为按钮留出空间
        
        # 保持宽高比缩放
        scaled_pixmap = self.original_pixmap.scaled(
            available_width,
            available_height,
            Qt.KeepAspectRatio,
            Qt.SmoothTransformation
        )
        
        self.image_label.setPixmap(scaled_pixmap)
            
    def resizeEvent(self, event):
        """窗口大小改变时重新调整图片大小"""
        super().resizeEvent(event)
        # 限制窗口最大尺寸
        if self.width() > self.max_width or self.height() > self.max_height:
            self.resize(
                min(self.width(), self.max_width),
                min(self.height(), self.max_height)
            )
        self.scale_image()

class DraggableLabel(QLabel):
    def __init__(self):
        super().__init__()
        self.setMouseTracking(True)
        self.drag_start = None
        self.scale_factor = 1.0
    
    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.drag_start = event.pos()
            self.setCursor(Qt.ClosedHandCursor)
    
    def mouseReleaseEvent(self, event):
        self.drag_start = None
        self.setCursor(Qt.ArrowCursor)
    
    def mouseMoveEvent(self, event):
        if self.drag_start is not None:
            delta = event.pos() - self.drag_start
            self.drag_start = event.pos()
            
            scrollarea = self.parent().parent()
            hbar = scrollarea.horizontalScrollBar()
            vbar = scrollarea.verticalScrollBar()
            
            hbar.setValue(hbar.value() - delta.x())
            vbar.setValue(vbar.value() - delta.y())
    
    def wheelEvent(self, event):
        if event.modifiers() == Qt.ControlModifier:
            delta = event.angleDelta().y()
            if delta > 0:
                self.scale_factor *= 1.1
            else:
                self.scale_factor /= 1.1
            self.update_image()
            event.accept()
        else:
            super().wheelEvent(event) 